<template>
    <div class="table-container">
  
      <el-form :model="queryParams" ref="searchForm" :inline="true" label-width="78px" style="margin-top: 30px;">
        <!-- 搜索栏内容 -->
        <el-form-item label="文件名称" prop="filename">
          <el-input v-model="queryParams.filename" placeholder="请输入文件名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- 搜索栏内容 -->
        <el-form-item label="文件路径" prop="filepath">
          <el-input v-model="queryParams.filepath" placeholder="请输入文件路径" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- 搜索栏内容 -->
        <el-form-item label="文件状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择文件状态" clearable @keyup.enter.native="handleQuery">
            <el-option label="等待上传" value="0"></el-option>
            <el-option label="上传中…" value="1"></el-option>
            <el-option label="上传成功" value="2"></el-option>
            <el-option label="上传失败" value="3"></el-option>
            <el-option label="上传取消" value="4"></el-option>
          </el-select>
        </el-form-item>
        <!-- 搜索按钮 -->
        <el-form-item style="margin-left: 20px;">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button type="primary" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <div class="button-group">
        <!-- 操作按钮组 -->
        <el-row>
          <el-button type="primary" icon="el-icon-plus" @click="handleOpenAddDialog">添加信息</el-button>
          <el-button type="danger" icon="el-icon-close" @click="handleBatchDelete" :disabled="selectedRowKeys.length === 0">批量删除</el-button>
          <el-button type="success" icon="el-icon-upload2" @click="handleBatchImport">批量导入</el-button>
          <el-button type="warning" icon="el-icon-download" @click="handleBatchExport">批量导出</el-button>
          <el-button class="blue-button" icon="el-icon-download" @click="handleAllExport">全量导出</el-button>
        </el-row>
      </div>
      <div>
        <input type="file" ref="fileInput" style="display: none" @change="handleFileChange" />
      </div>
      <!-- 数据表格 -->
      <el-table @selection-change="handleSelectionChange" @row-click="handleRowClick" ref="multipleTable" row-key="id" :data="uploadLogList" border style="width: 100%;" header-align="center">
        <!-- 多选框 -->
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="120" align="center"></el-table-column>
         <!-- 上传时间列 -->
        <el-table-column prop="uploadtime" label="账期" align="center"></el-table-column>
        <!-- 文件名列 -->
        <el-table-column prop="filename" label="部门" align="center"></el-table-column>
        <!-- 文件路径列 -->
        <el-table-column prop="filepath" label="姓名" align="center"></el-table-column>
       
        <!-- 文件状态列 -->
        <el-table-column prop="status" label="发布状态" align="center">
          <template slot-scope="scope">
            <div :class="getStatusClass(scope.row)">
              {{ formatStatus(scope.row) }}
            </div>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="240" align="center">
          <template slot-scope="{ row, $index }">
            <!-- 修改按钮 -->
            <el-button type="warning" icon="el-icon-edit" size="mini" @click="openEditDialog(row)">修改</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUploadLog(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页器 -->
      <el-pagination background style="margin-top: 20px; text-align: center;" :current-page.sync="queryParams.pageNum" :page-size.sync="queryParams.pageSize" :total="total" :pager-count="7" :page-sizes="[10, 20, 50]"
        @size-change="getPageList" @current-change="getPageList" prev-text="上一页" next-text="下一页" layout="prev, pager, next, jumper,->,sizes,total">
      </el-pagination>
  
      <!-- 添加/编辑表单的弹出框 -->
      <el-dialog :visible="dialogVisible" :title="dialogTitle" @close="closeDialog" append-to-body>
        <el-form :model="addOrEditForm" label-width="80px" ref="addOrEditForm">
          <!-- 文件名输入框 -->
          <el-form-item label="文件名">
            <el-input v-model="addOrEditForm.filename"></el-input>
          </el-form-item>
          <!-- 文件路径输入框 -->
          <el-form-item label="文件路径">
            <el-input v-model="addOrEditForm.filepath"></el-input>
          </el-form-item>
          <!-- 上传时间选择器 -->
          <el-form-item label="上传时间">
            <el-date-picker default-current-value :default-value="defaultTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" v-model="addOrEditForm.uploadtime" style="width: 100%;"></el-date-picker>
          </el-form-item>
          <!-- 文件状态选择框 -->
          <el-form-item label="文件状态">
            <el-select v-model="addOrEditForm.status" placeholder="请选择">
              <el-option label="等待上传" :value="0"></el-option>
              <el-option label="上传中…" :value="1"></el-option>
              <el-option label="上传成功" :value="2"></el-option>
              <el-option label="上传失败" :value="3"></el-option>
              <el-option label="上传取消" :value="4"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!-- 弹出框底部按钮 -->
        <div slot="footer" class="dialog-footer">
          <!-- 保存按钮 -->
          <el-button @click="saveForm" type="primary">{{ dialogAction }}</el-button>
          <!-- 取消按钮 -->
          <el-button @click="closeDialog">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  export default {
    name: "UploadLogTable",
    data() {
      return {
        // 查询参数
        queryParams: {
          // 代表的是分页器是第几页，默认第一页
          pageNum: 1,
          // 当前页面展示数据的条数
          pageSize: 10,
          // 模糊查询的条件
          filename: null,
          // 文件路径的查询条件
          filepath: null,
          // 文件状态的查询条件
          status: null,
        },
        // 数据的总共多少条
        total: 0,
        // 返回数据列表
        uploadLogList: [],
        // 弹出框可见性
        dialogVisible: false,
        // 弹出框标题
        dialogTitle: "",
        // 弹出框按钮文字
        dialogAction: "",
        // 添加/编辑表单数据对象
        addOrEditForm: {},
        // 返回的是选中的列的数组集合
        selectedRowKeys: [],
        //默认时间
        defaultTime: new Date(),
      };
    },
    mounted() {
      // 获取列表数据方法
      this.getPageList();
    },
    methods: {
      /** 查询分类列表 */
      getPageList() {
        this.$API.upload
          .listfileInfo(this.queryParams)
          .then((response) => {
            // 处理返回的结果
            this.uploadLogList = response.data.list;
            this.total = response.data.total;
          })
          .catch((error) => {
            // 处理错误信息
            console.error("请求失败：", error);
          });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getPageList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.filename = "";
        this.queryParams.filepath = "";
        this.queryParams.status = "";
        this.handleQuery();
      },
  
      /****  【3】格式化转换状态 ****/
      formatStatus(row) {
        switch (row.status) {
          case 0:
            return "等待上传";
          case 1:
            return "上传中…";
          case 2:
            return "上传成功";
          case 3:
            return "上传失败";
          case 4:
            return "上传取消";
          default:
            return "未知状态";
        }
      },
      getStatusClass(row) {
        switch (row.status) {
          case 0:
            return "status-pending";
          case 1:
            return "status-uploading";
          case 2:
            return "status-success";
          case 3:
            return "status-failed";
          case 4:
            return "status-canceled";
          default:
            return "status-unknown";
        }
      },
      /**** 【4】添加弹出框 ****/
      handleOpenAddDialog() {
        this.dialogTitle = "添加信息";
        this.dialogAction = "添加";
        this.addOrEditForm = {
          uploadtime: this.getCurrentDateTime(),
          status: 0,
        };
        this.dialogVisible = true;
      },
      /**** 【5】获取当前时间 ****/
      getCurrentDateTime() {
        let currentDateTime = new Date();
        let year = currentDateTime.getFullYear();
        let month = ("0" + (currentDateTime.getMonth() + 1)).slice(-2);
        let day = ("0" + currentDateTime.getDate()).slice(-2);
        let hours = ("0" + currentDateTime.getHours()).slice(-2);
        let minutes = ("0" + currentDateTime.getMinutes()).slice(-2);
        let seconds = ("0" + currentDateTime.getSeconds()).slice(-2);
  
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
      /**** 【6.1】修改弹出框 ****/
      openEditDialog(row) {
        this.dialogTitle = "修改信息";
        this.dialogAction = "保存";
        this.addOrEditForm = Object.assign({}, row);
        this.addOrEditForm.status = row.status; // 根据 row.status 的值设置 addOrEditForm.status 的初始值
        this.dialogVisible = true;
      },
      /**** 【6.2】关闭弹出框 ****/
      closeDialog() {
        this.dialogVisible = false;
      },
      /**** 【7】弹出框保存数据 ****/
      async saveForm() {
        try {
          const isValid = await this.$refs.addOrEditForm.validate();
          if (isValid) {
            if (this.dialogAction === "添加") {
              const result = await this.$API.upload.addInfo(this.addOrEditForm);
              if (result.code === 200) {
                this.$message.success("添加成功");
                this.dialogVisible = false;
                // 计算出最后一页的页码
                const pageLastNum = Math.ceil(
                  this.total / this.queryParams.pageSize
                );
                this.getPageList(pageLastNum);
                // 保存完以后，跳转到最后一页
                this.queryParams.pageNum = pageLastNum;
              } else {
                this.$message.error("添加失败");
              }
            } else {
              const result = await this.$API.upload.updateInfo(
                this.addOrEditForm
              );
              if (result.code === 200) {
                this.$message.success("修改成功");
                this.dialogVisible = false;
                this.getPageList(this.page);
              } else {
                this.$message.error("修改失败");
              }
            }
          }
        } catch (error) {
          console.error(error);
          this.$message.error("保存失败");
        }
        // 保存完以后，清除选中的项
        this.$refs.multipleTable.clearSelection();
      },
      /****【8】删除数据 ****/
      // 将 deleteUploadLog 方法修改为以下形式
      async deleteUploadLog(row) {
        try {
          await this.$confirm(`请确定要删除【${row.filename}】吗？`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          });
  
          const result = await this.$API.upload.deleteInfo(row.id);
          if (result.code === 200) {
            this.$message.success(`【${row.filename}】的数据删除成功`);
            this.getPageList(
              this.uploadLogList.length > 1 ? this.page : this.page - 1
            );
          } else {
            this.$message.error(`【${row.filename}】的数据删除失败`);
          }
        } catch (error) {
          console.error(error);
          this.$message.error(`【${row.filename}】的数据删除失败`);
        }
      },
      /****【9】执行批量删除操作 ****/
      // 【9.1】点击复选框触发，复选框样式的改变
      handleSelectionChange(val) {
        this.selectedRowKeys = val;
      },
      // 【9.2】点击行触发，选中或不选中复选框
      handleRowClick(row) {
        this.$refs.multipleTable.toggleRowSelection(row);
      },
      // 【9.3】点击批量删除
      async handleBatchDelete() {
        const { selectedRowKeys: selectedRows } = this;
        try {
          // 弹出确认对话框
          await this.$confirm(`请确定要删除选中的数据吗？`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          });
  
          // 构建删除操作的数组
          const results = await Promise.allSettled(
            selectedRows.map((row) => this.$API.upload.deleteInfo(row.id))
          );
  
          // 检查是否有成功删除的数据
          if (results.some((result) => result.status === "fulfilled")) {
            // 更新表格数据
            this.getPageList(
              this.uploadLogList.length > 1 ? this.page : this.page - 1
            );
            // 清空选中的行数据
            this.selectedRowKeys = [];
            this.$message.success("选中的数据批量删除成功");
          } else {
            this.$message.warning("没有成功删除的数据");
          }
        } catch (error) {
          console.error(error);
          this.$message.error("批量删除失败");
        }
      },
  
      /****【10】全量批量导出表格所选数据 ****/
      async handleAllExport() {
        await this.$confirm(`请确定要导出选中的数据吗？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        await this.$API.upload
          .exportAllInfo()
          .then((response) => {
            this.downloadFile(response, "全量信息.xlsx");
          })
          .catch((error) => {
            console.error("导出Excel失败", error);
          });
      },
      /****  【11】批量导出表格所选数据 ****/
      async handleBatchExport() {
        const { selectedRowKeys } = this;
        if (selectedRowKeys.length === 0) {
          this.$message.warning("请选择要导出的数据");
          return;
        }
        try {
          await this.$confirm(`请确定要导出选中的数据吗？`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          });
          const exportIds = selectedRowKeys.map((row) => row.id).join(",");
          const response = await this.$API.upload.exportBatchInfo(exportIds);
          this.downloadFile(response, "上传日志.xlsx");
          this.$message.success("导出数据成功");
        } catch (error) {
          console.error("导出数据失败:", error);
          this.$message.error("导出数据失败");
        }
      },
      /**** 【12】通过 HTTP 响应获取的文件内容进行下载操作 ****/
      downloadFile(response, fileName) {
        const url = window.URL.createObjectURL(new Blob([response]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
      },
      /**** 【13】执行批量导入操作 ****/
      handleBatchImport() {
        this.$refs.fileInput.click(); // 触发文件选择对话框
      },
  
      async handleFileChange(event) {
        try {
          const files = event.target.files;
  
          if (files.length > 0) {
            const formData = new FormData();
            formData.append("file", files[0]); // 将文件添加到 FormData 对象中
            await this.uploadFile(formData); // 调用上传文件方法
            this.$message.success("文件上传成功"); // 弹出成功消息
            this.getPageList(); // 更新页面数据
          } else {
            throw new Error("请选择要上传的文件");
          }
        } catch (error) {
          console.error("文件上传失败", error);
          this.$message.error("文件上传失败：" + error.message); // 弹出失败消息
        } finally {
          // 计算出最后一页的页码
          const pageLastNum = Math.ceil(this.total / this.queryParams.pageSize);
          // 保存完以后，跳转到最后一页
          this.queryParams.pageNum = pageLastNum;
          event.target.value = ""; // 清空文件选择框的值
        }
      },
  
      async uploadFile(formData) {
        try {
          const response = await this.$API.upload.uploadFiles(formData);
          console.log("文件上传成功", response);
        } catch (error) {
          throw new Error("文件上传失败：" + error.message);
        }
      },
    },
  };
  </script>
  
  <style>
  .table-container {
    width: 98%;
  }
  
  .Search {
    width: 20%;
  }
  
  .table-container .el-table {
    border-radius: 8px; /* 圆角 */
    overflow: hidden; /* 隐藏边角 */
    /* margin: 0 10px; */
  }
  
  .table-container .el-table th {
    background-color: #9cbc5f; /* 表头背景色 */
    color: #ffffff; /* 表头文字色 */
    border-bottom-width: 0;
    font-size: 16px;
  }
  
  .table-container .el-table tbody tr {
    font-size: 17px; /* 所有行统一字体大小 */
    font-weight: 500;
  }
  
  .table-container .el-table tbody tr:nth-child(odd) {
    background: #ffffff; /* 奇数行背景色 */
  }
  
  .table-container .el-table tbody tr:nth-child(even) {
    background-color: #f0fbe0; /* 偶数行背景色 */
  }
  
  /* 去掉原来鼠标悬浮效果 */
  .el-table tbody tr:hover > td {
    background-color: transparent !important
  }
  
  .table-container .el-table tbody tr:hover {
    background-color: #e8f8b8 !important; /* 悬停时的背景色 */
  }
  
  .button-group {
    margin: 20px 0; /* 合并上下间距 */
    text-align: right;
  }
  
  .blue-button {
    background-color: #f38b03;
    color: aliceblue;
  }
  
  .dialog-footer {
    text-align: right;
  }
  
  .status-pending { color: #646664 !important; } /* 等待上传 */
  .status-uploading { color: #43b8ee !important; } /* 上传中… */
  .status-success { color: #4caf50 !important; } /* 上传成功 */
  .status-failed { color: #f44336 !important; } /* 上传失败 */
  .status-canceled { color: #eb0808 !important; } /* 上传取消 */
  .status-unknown { color: #757575 !important; } /* 未知状态 - 暗灰色 */
  </style>
  